package com.Alan.servlet.order;

import com.Alan.pojo.Order;
import com.Alan.pojo.Role;
import com.Alan.pojo.Supplier;
import com.Alan.pojo.User;
import com.Alan.service.order.OrderService;
import com.Alan.service.order.OrderServiceImpl;
import com.Alan.service.role.RoleService;
import com.Alan.service.role.RoleServiceImpl;
import com.Alan.service.supplier.SupplierService;
import com.Alan.service.supplier.SupplierServiceImpl;
import com.Alan.service.user.UserService;
import com.Alan.service.user.UserServiceImpl;
import com.Alan.util.Constants;
import com.Alan.util.Paging;
import com.Alan.util.UtilsAlan;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderServlet extends HttpServlet {

    public OrderServlet (){super();}

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (!StringUtils.isNullOrEmpty(method)){
            switch (method){
                case "getOrdList":
                    this.getOrdList(req, resp);
                    break;
                case "ordInformation":
                    this.ordInformation(req, resp);
                    break;
                case "ordCodeExist":
                    this.ordCodeExist(req, resp);
                    break;
                case "getSupNames":
                    this.getSupNames(req, resp);
                    break;
                case "addOrd":
                    this.addOrd(req, resp);
                    break;
                case "updateOrdSubmit":
                    this.updateOrdSubmit(req, resp);
                    break;
                case "updateOrd":
                    this.updateOrd(req, resp);
                    break;
                default:
                    System.out.println();
            }
        }
        
    }

    private void getOrdList(HttpServletRequest req, HttpServletResponse resp) {
        Paging paging = new Paging();

        String ordName = req.getParameter("queryOrdName");
        String querySupId  = req.getParameter("querySupId");
        String isPay  = req.getParameter("queryOrdIsPay");
        String pageIndex = req.getParameter("pageIndex");
        int supId = 0;

        if (StringUtils.isNullOrEmpty(ordName)){
            ordName = "";
        }
        if (!StringUtils.isNullOrEmpty(querySupId)){
            supId = Integer.parseInt(querySupId);
        }
        if (StringUtils.isNullOrEmpty(isPay)){
            isPay = "";
        }
        if (!StringUtils.isNullOrEmpty(pageIndex)) {
            paging.setPageIndex(Integer.parseInt(pageIndex));
        }

//        获取订单列表
        OrderService orderService = new OrderServiceImpl();
        List<Order> ordList = orderService.getOrderList(ordName, isPay, supId, paging.getStartRow(), paging.getPageRows());
        //        获取用户总数并添加到Paging
        int ordCount = orderService.getOrderCount(ordName, isPay, supId);
        paging.setAllSize(ordCount);

//        获取所有供应商名字
        SupplierService supplierService = new SupplierServiceImpl();
        List<Supplier> supNames = supplierService.getSupNames();

//        返回前端数据
        req.setAttribute("ordList", ordList);
        req.setAttribute("supNames", supNames);
        req.setAttribute("pageCount", paging.getPageCount());
        req.setAttribute("allSize", paging.getAllSize());
        req.setAttribute("pageIndex", paging.getPageIndex());


//        返回前端
        try {
            System.out.println("orderList");
            req.getRequestDispatcher(req.getContextPath() + "/JSP/orderList.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR:OrderServlet -> getOrdList");
        }

    }

    private void ordInformation(HttpServletRequest req, HttpServletResponse resp) {
        int ordId = Integer.parseInt(req.getParameter("ordId"));

        OrderService orderService = new OrderServiceImpl();
        Order ord = orderService.getOrderInformation(ordId);

        req.setAttribute("ord", ord);
        try {
            req.getRequestDispatcher(req.getContextPath() + "/JSP/orderInformation.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR:OrderServlet -> ordInformation");
        }

    }

    private void ordCodeExist(HttpServletRequest req, HttpServletResponse resp) {
        String ordCode = req.getParameter("ordCode");
        Map<String, String> resultMap = new HashMap<>();

        if (!StringUtils.isNullOrEmpty(ordCode)){
            OrderService orderService = new OrderServiceImpl();
            if (orderService.orderExist(ordCode)){
                resultMap.put("ordCode", "exist");
            }else {
                resultMap.put("ordCode", "notExist");
            }
        }else {
            resultMap.put("ordCode", "exist");
        }
//把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        resp.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = null;
        try {
            outPrintWriter = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("UserServlet -> verifyUserCodeExist");
        }
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流

    }

    private void getSupNames(HttpServletRequest req, HttpServletResponse resp) {
        SupplierService supplierService = new SupplierServiceImpl();
        List<Supplier> supNames = supplierService.getSupNames();
//        返回json格式
        resp.setContentType("application/json; charset=UTF-8");
        try {
            PrintWriter outPrintWriter = resp.getWriter();
            outPrintWriter.write(JSONArray.toJSONString(supNames));
            outPrintWriter.flush();
            outPrintWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("OrderServlet -> getSupNames");
        }
    }

    private void addOrd(HttpServletRequest req, HttpServletResponse resp) {
        Order order = new Order();
        order.setOrdCode(req.getParameter("ordCode"));
        order.setOrdName(UtilsAlan.transCoding(req.getParameter("ordName"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        order.setCount(new BigDecimal(req.getParameter("count")));
        order.setUnit(UtilsAlan.transCoding(req.getParameter("unit"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        order.setTotalPrice(new BigDecimal(req.getParameter("totalPrice")));
        order.setIsPay(UtilsAlan.transCoding(req.getParameter("isPay"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        order.setDescribe(UtilsAlan.transCoding(req.getParameter("describe"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        order.setSupId(Integer.parseInt(req.getParameter("supId")));
        order.setCreatedByUserCode(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getUserCode());
        order.setCreatedByUserName(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getUserName());
        order.setCreationDate(UtilsAlan.strToSqlDate(UtilsAlan.getNowDateStr(), true));

        System.out.println("获取前端数据成功");
        OrderService orderService = new OrderServiceImpl();
        if (orderService.addOrder(order)) {
            try {
                resp.sendRedirect(req.getContextPath() + "/JSP/ord.go?method=getOrdList");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("OrderServlet -> addOrd");
            }
        } else {
            try {
                req.getRequestDispatcher(req.getContextPath() + "/JSP/orderAdd.jsp").forward(req, resp);
                req.setAttribute(Constants.MESSAGE, "添加失败，请退出重试");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("OrderServlet -> addOrd");
            }
        }
    }

    private void updateOrdSubmit(HttpServletRequest req, HttpServletResponse resp) {
        Order order = new Order();
        order.setId(Integer.parseInt(req.getParameter("ordId")));
        order.setOrdCode(req.getParameter("ordCode"));
        order.setOrdName(UtilsAlan.transCoding(req.getParameter("ordName"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        order.setCount(new BigDecimal(req.getParameter("count")));
        order.setUnit(UtilsAlan.transCoding(req.getParameter("unit"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        order.setTotalPrice(new BigDecimal(req.getParameter("totalPrice")));
        order.setIsPay(UtilsAlan.transCoding(req.getParameter("isPay"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        order.setDescribe(UtilsAlan.transCoding(req.getParameter("describe"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
//        order.setSupId(Integer.parseInt(req.getParameter("supId")));
        order.setModifyByUserCode(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getUserCode());
        order.setModifyByUserName(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getUserName());
        order.setModifyDate(UtilsAlan.strToSqlDate(UtilsAlan.getNowDateStr(), true));


        OrderService orderService = new OrderServiceImpl();

        if (orderService.updateOrder(order)){
            System.out.println("true");
            try {
                resp.sendRedirect(req.getContextPath() + "/JSP/ord.go?method=getOrdList");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("OrderServlet -> updateOrdSubmit");
            }
        } else {
            System.out.println("false");
            try {
                req.getRequestDispatcher(req.getContextPath() + "/JSP/updateOrder.jsp").forward(req, resp);
                req.setAttribute(Constants.MESSAGE, "修改失败，请退出重试");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("UserServlet -> updateOrdSubmit");
            }
        }
    }

    private void updateOrd(HttpServletRequest req, HttpServletResponse resp) {
        int ordId = Integer.parseInt(req.getParameter("ordId"));

        OrderService orderService = new OrderServiceImpl();
        Order ord = orderService.getOrderInformation(ordId);

        req.setAttribute("ord", ord);
        try {
            req.getRequestDispatcher(req.getContextPath() + "/JSP/orderUpdate.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR:OrderServlet -> updateOrd");
        }
    }
}
